package com.xmb.wechat.widget;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.ArrayMap;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.chad.library.adapter.base.BaseViewHolder;
import com.xmb.wechat.R;
import com.xmb.wechat.common.Constant;
import com.xmb.wechat.definterface.SimpleTextWatcher;
import com.xmb.wechat.util.EmotionUtils;
import com.xmb.wechat.util.SpanStringUtils;

/**
 * @Author lijiangop
 * @CreateTime 2020/4/11 16:10
 */
public class ChartBar extends RelativeLayout {

    private View      mView;
    private EditText  mEtInput;
    private Button    mBtnSend;
    private ImageView mIvVoice, mIvEmo, mIvAdd;
    private OnChatBarClickCallBack mCallBack;
    private RelativeLayout         mReConsole;

    //表情
    private RelativeLayout mLayoutFace;
    private RecyclerView   mRecyclerView;
    private ImageView      mIvDelete;

    public ChartBar(Context context) {
        this(context, null);
    }

    public ChartBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ChartBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        mView = LayoutInflater.from(context).inflate(R.layout.layout_chat_bar, null, false);
        //顶部
        mReConsole = mView.findViewById(R.id.re_console);
        mIvVoice = mView.findViewById(R.id.btn_voice);
        mEtInput = mView.findViewById(R.id.et_input);
        mIvEmo = mView.findViewById(R.id.btn_emo);
        //顶部右边
        mIvAdd = mView.findViewById(R.id.btn_add);
        mBtnSend = mView.findViewById(R.id.btn_send);
        //表情
        mLayoutFace = mView.findViewById(R.id.layout_face);
        mRecyclerView = mView.findViewById(R.id.recyclerView);
        mIvDelete = mView.findViewById(R.id.iv_delete);

        //点击事件
        mIvVoice.setOnClickListener(v -> {
            if (mCallBack != null)
                mCallBack.onVoiceClick();
        });
        mIvEmo.setOnClickListener(v -> {
            switchView(mLayoutFace.getVisibility() == VISIBLE);
        });
        mIvAdd.setOnClickListener(v -> {
            if (mCallBack != null)
                mCallBack.onAddClick();
        });
        mBtnSend.setOnClickListener(v -> {
            if (mCallBack != null)
                mCallBack.onSendClick();
        });
        mEtInput.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                switchView(true);
                mEtInput.requestFocus();
            }
        });
        //监听
        mEtInput.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChangedFinish(String value) {
                if (value.length() > 0)
                    mBtnSend.setVisibility(View.VISIBLE);
                else
                    mBtnSend.setVisibility(View.GONE);
            }
        });
        mBtnSend.setOnLongClickListener(v -> {
            if (mCallBack != null)
                mCallBack.onSendLongClick(mEtInput.getText().toString().trim());
            return true;
        });
        addView(mView, new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    }

    /**
     * 调整View大小
     */
    public void adjustViewSize() {
        int fontScaleLevel = SPUtils.getInstance().getInt(Constant.SP.SP_KEY_FONT_SCALE_LEVEL, Constant.SP.SP_DEFAULT_FONT_SCALE_LEVEL);
        //textView
        if (fontScaleLevel < Constant.mChatBarCommonTextScale.length) {
            mEtInput.setTextSize(Constant.mChatBarCommonTextScale[fontScaleLevel] * 17);
        }
        //btnSend
        if (fontScaleLevel < Constant.mChatBarBtnSendScale.length) {
            mBtnSend.setTextSize(Constant.mChatBarBtnSendScale[fontScaleLevel] * 17);
        }
        if (fontScaleLevel < Constant.mChatBarCommonScale.length) {
            //ivVoice
            int imageResult = Float.valueOf(SizeUtils.dp2px(28f) * Constant.mChatBarCommonScale[fontScaleLevel]).intValue();
            ViewGroup.LayoutParams voicelayoutParams = mIvVoice.getLayoutParams();
            voicelayoutParams.width = imageResult;
            voicelayoutParams.height = imageResult;
            mIvVoice.setLayoutParams(voicelayoutParams);
            //ivEmo
            ViewGroup.LayoutParams emolayoutParams = mIvEmo.getLayoutParams();
            emolayoutParams.width = imageResult;
            emolayoutParams.height = imageResult;
            mIvEmo.setLayoutParams(emolayoutParams);
            //ivAdd
            ViewGroup.LayoutParams addlayoutParams = mIvAdd.getLayoutParams();
            addlayoutParams.width = imageResult;
            addlayoutParams.height = imageResult;
            mIvAdd.setLayoutParams(addlayoutParams);
            //btnSend
            int btnSendHeight = Float.valueOf(SizeUtils.dp2px(32f) * Constant.mChatBarCommonScale[fontScaleLevel]).intValue();
            ViewGroup.LayoutParams sendlayoutParams = mBtnSend.getLayoutParams();
            sendlayoutParams.width = (int) (btnSendHeight * 1.95f);
            sendlayoutParams.height = btnSendHeight;
            mBtnSend.setLayoutParams(sendlayoutParams);
            //console
            ViewGroup.LayoutParams consoleLayoutParams = mReConsole.getLayoutParams();
            consoleLayoutParams.height = Float.valueOf(ScreenUtils.getScreenWidth() * 0.142f * Constant.mChatBarCommonScale[fontScaleLevel]).intValue();
            mReConsole.setLayoutParams(consoleLayoutParams);
        }
    }

    /**
     * 切换表情或输入键盘
     */
    private void switchView(boolean isEmojiVisible) {
        if (isEmojiVisible) {
            mLayoutFace.setVisibility(GONE);
            mIvEmo.setImageDrawable(getResources().getDrawable(R.drawable.wechat_input_emoticon1380));
            KeyboardUtils.showSoftInput(this);
        } else {
            KeyboardUtils.hideSoftInput(this);
            postDelayed(() -> mLayoutFace.setVisibility(VISIBLE), 50);
            mIvEmo.setImageDrawable(getResources().getDrawable(R.drawable.wechat_input_key_bord));
        }
    }

    /**
     * 初始化
     *
     * @param context
     * @param callBack
     */
    public void init(Context context, OnChatBarClickCallBack callBack) {
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT)
            return;
        mCallBack = callBack;
        //initEmoji
        ArrayMap data = EmotionUtils.getData();
        NewEmojiAdapter adapter = new NewEmojiAdapter(context, data, new OnEmojiListener() {
            @Override
            public void onItemClick(String key) {
                int curPosition = mEtInput.getSelectionStart();
                StringBuilder sb = new StringBuilder(mEtInput.getText().toString());
                sb.insert(curPosition, key);
                mEtInput.setText(SpanStringUtils.getEmotionContent(context, mEtInput, sb.toString()));
                mEtInput.setSelection(curPosition + key.length());
            }
        });
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setLayoutManager(new GridLayoutManager(context, 8));
        mIvDelete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEtInput == null)
                    return;
                KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
                mEtInput.dispatchKeyEvent(event);
            }
        });
    }

    //-----------------------------------------------------------------------------面向外部方法 开始-------------------------------------------------------------------------
    //获取发送内容
    public String getSendValue() {
        return mEtInput == null ? "" : mEtInput.getText().toString().trim();
    }

    //清除输入法
    public void clearInput() {
        if (mEtInput != null)
            mEtInput.setText("");
    }

    //隐藏表情和输入法
    public void hideExpand() {
        if (mLayoutFace != null && mLayoutFace.getVisibility() == VISIBLE) {
            mLayoutFace.setVisibility(GONE);
            if (mIvEmo != null)
                mIvEmo.setImageDrawable(getResources().getDrawable(R.drawable.wechat_input_emoticon1380));
        }
        KeyboardUtils.hideSoftInput(this);
    }

    //表情模块是否显示
    public boolean isEmojiVisible() {
        return mLayoutFace != null && mLayoutFace.getVisibility() == VISIBLE;
    }

    //------------------------------------------------------------------------------面向外部方法 结束--------------------------------------------------------"

    //接口
    public interface OnChatBarClickCallBack {
        void onVoiceClick();

        void onAddClick();

        void onSendClick();

        void onSendLongClick(String msg);
    }

    public interface OnEmojiListener {
        void onItemClick(String key);
    }

    //表情adapter
    private class NewEmojiAdapter extends RecyclerView.Adapter {

        private OnEmojiListener mListener;
        private Context         mContext;
        private ArrayMap        mData;

        public NewEmojiAdapter(Context context, ArrayMap datas, OnEmojiListener listener) {
            mContext = context;
            mData = datas;
            mListener = listener;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View inflate = LayoutInflater.from(mContext).inflate(R.layout.item_emoji, viewGroup, false);
            return new EmojiViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                EmojiViewHolder holder = (EmojiViewHolder) viewHolder;
                String key = (String) mData.keyAt(i);
                Integer res = (Integer) mData.get(key);
                if (res > -1) {
                    holder.imageView.setImageResource(res);
                    holder.itemView.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null)
                                mListener.onItemClick(key);
                        }
                    });
                }
            }
        }

        @Override
        public int getItemCount() {
            return mData == null ? 0 : mData.size();
        }

        class EmojiViewHolder extends BaseViewHolder {

            ImageView imageView;

            public EmojiViewHolder(View inflate) {
                super(inflate);
                imageView = itemView.findViewById(R.id.iv_emoji);
            }
        }
    }
}
